package com.sljy.hzk.ui.exam;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.sljy.hzk.R;
import com.sljy.hzk.annotation.ActivityInfo;
import com.sljy.hzk.base.BaseActivity;
import com.sljy.hzk.base.UserInfo;
import com.sljy.hzk.entity.ExamHistotyEntity;
import com.sljy.hzk.entity.ExamMainEntity;
import com.sljy.hzk.entity.UserEntity;
import com.sljy.hzk.net.BaseCallBack;
import com.sljy.hzk.net.CommonResult;
import com.sljy.hzk.net.HttpHeper;
import com.sljy.hzk.net.service.ExamService;
import com.sljy.hzk.room.AppDataBase;
import com.sljy.hzk.ui.QrCodeActivity;
import com.sljy.hzk.ui.fragment.ExamHistoryFragment;
import com.sljy.hzk.ui.fragment.ExamPlanFragment;
import com.sljy.hzk.util.TimeUtils;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@ActivityInfo(layout = R.layout.activity_exam_main, isShowActionBar = true,title = "历史记录",rightIcRes = R.drawable.homepage)
public class ExamMainActivity extends BaseActivity {
    @BindArray(R.array.exam_tab)
    String[] titles;
    @BindView(R.id.tablayout)
    TabLayout tablayout;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    private List<Fragment> fragments = new ArrayList<>();
    UserEntity user;

    @Override
    protected void init() {
        user = UserInfo.getUserInfo();
         //.getAllExam( user.getCpId(), user.getPId())

        loadData(1);

    }

    private void loadData(int type){
        if(fragments.size() > 0){
            fragments.remove(0);
            fragments.remove(0);
        }
        HttpHeper.get().create(ExamService.class)
                .getAllExam(user.getComPId(), user.getCpId(), 1)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.newThread())
                //进行分组,插入头部,今天明天后天需要单独处理
                .map(data -> {
                    return data;
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseCallBack<ExamHistotyEntity>(this){
                    @Override
                    public void onCallBackSuccess(ExamHistotyEntity data) {
                        //fragments.add(ExamPlanFragment.get(data.getExamList()));
                        if(data.getValue() == null)
                            data.setValue(new ArrayList<ExamHistotyEntity.ExamInfo>());
                        fragments.add(ExamHistoryFragment.get(data.getValue()));
                        fragments.add(ExamHistoryFragment.get(data.getValue()));
                        initFragment();
                    }

                    @Override
                    public void onFail(String mes) {
                        showToast(mes);
                    }
                });

//        Call<CommonResult<Object>> result = HttpHeper.get().create(ExamService.class). getAllExam(user.getComPId(), user.getCpId(), 1);
//        result.enqueue( new Callback<CommonResult<Object>>(){
//            @Override
//            public void onResponse(Call<CommonResult<Object>> call, Response<CommonResult<Object>> response) {
//                if(response.isSuccessful()){
//                    Gson json = new Gson();
//                    List<ExamHistotyEntity> list = json.fromJson(response.body().getData().toString(),new TypeToken<List<ExamHistotyEntity>>() {}.getType());
//                    Log.i(TAG,"上传成功"+response.body().getData());
//                }else {
//                    Log.i(TAG,"上传失败");
//                }
//            }
//            @Override
//            public void onFailure(Call<CommonResult<Object>> call, Throwable t) {
//                Log.e(TAG,"上传失败");
//            }
//        });

    }


    void initFragment(){

        if(viewpager.getAdapter() != null)
            return;
        viewpager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return titles[position];
            }
        });
        tablayout.setupWithViewPager(viewpager);
        tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if(tab.getPosition() == 0)
                    loadData(1);
                else
                    loadData(2);
                viewpager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    /**
     * 扫描
     */
    @OnClick(R.id.scanning)
    void  scanning(){
        //ExamYzActivity__JumpCenter.builder(this).setExamId("31?0").create().go();
        new IntentIntegrator(this)
                .setCaptureActivity(QrCodeActivity.class)
                .setPrompt("请对准二维码")
                .setCameraId(0)
                .initiateScan();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(result != null) {
            if(result.getContents() != null) {
               String url =  result.getContents();
                String examId =  analysisUrl(url,"homePage?examId=");
                if(examId == null){
                    examId =  analysisUrl(url,"html?examId=");
                    if(examId != null)
                        examId = examId+"?0";
                    //签到
                }
                //考试
                if (TextUtils.isEmpty(examId)) showToast("请扫描正确的二维码");
                else ExamYzActivity__JumpCenter.builder(this).setExamId(examId).create().go();
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }


    /**
     * 解析扫描得到的url，分解出examId
     * @param url
     */
    private String analysisUrl(String url, String path){
        String examId = null;
        String includeStr = path;
        if (url.contains(includeStr)){
            int first1=url.indexOf(includeStr);
            //从索引处到末尾（不包括索引处）
            String substr1=url.substring(first1);
            Log.d(TAG, ">>>substr1---" + substr1);
            int first2=substr1.indexOf("=");
            examId = substr1.substring(first2+1);
            Log.d(TAG, ">>>examId---" + examId);
        }
        return examId;
    }
}
